﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics.Metrics;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using ServiceStack.Redis;

namespace CICDk8s.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
      private readonly  ILogger<TestController> _logger;
        private readonly IHttpClientFactory _clientFactory;
        private readonly Meter _greeterMeter;
        private readonly ActivitySource _greeterActivitySource;
        public TestController(ILogger<TestController> logger, IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
            _logger = logger;
            #region  OpenTelemetry 监控
            // Custom metrics for the application
            _greeterMeter = new Meter("监控Meter.Test", "1.0.0");
            // Custom ActivitySource for the application
            _greeterActivitySource = new ActivitySource("监控Activity.Test");
            #endregion
        }
        [HttpGet("version")]
        public string Version()
        {
            string hostName = Dns.GetHostName();
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
            IPAddress[] addresses = hostEntry.AddressList;
            string ip = string.Empty;
            foreach (IPAddress address in addresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = ip + "," + address.ToString();
                }
            }
            int[] arr = { 1, 2, 3, 4, 5 };
            foreach (ref int v in arr.AsSpan())
            { v++; }
            var ss = string.Join(",", arr);

            //using (RedisClient client = new RedisClient("192.168.0.204"))//, 6379, "p12345"))
            //{
            //    client.AddItemToList("listlog", "test 写log" + DateTimeOffset.UtcNow);
            //}

            return "version:v8 t " + "；IP：" + ip + "。时间：" + DateTime.Now;
        }
        [HttpGet("count")]
        public async Task<String> SendGreeting()
        {
            var countGreetings = _greeterMeter.CreateCounter<int>("greetings.count", description: "Counts the number of greetings");
            // Create a new Activity scoped to the method
            using var activity = _greeterActivitySource.StartActivity("GreeterActivity");

            // Log a message
            _logger.LogInformation("Sending greeting 日志");

            // Increment the custom counter
            countGreetings.Add(1);

            // Add a tag to the Activity
            activity?.SetTag("greeting", "Hello World!");

            return "Hello World!" + DateTime.Now;
        }
        [HttpGet("NestedGreeting")]
        public async Task SendNestedGreeting(int nestlevel)
        {
            // Create a new Activity scoped to the method
            using var activity = _greeterActivitySource.StartActivity("GreeterActivity");

            if (nestlevel <= 5)
            {
                // Log a message
                _logger.LogInformation("Sending greeting, level {nestlevel}", nestlevel);

                var countGreetings = _greeterMeter.CreateCounter<int>("greetings.count", description: "Counts the number of greetings");
                // Increment the custom counter
                countGreetings.Add(1);

                // Add a tag to the Activity
                activity?.SetTag("nest-level", nestlevel);

                await HttpContext.Response.WriteAsync($"Nested Greeting, level: {nestlevel}\r\n");

                if (nestlevel > 0)
                {
                    var request = HttpContext.Request;
                    var url = new Uri($"{request.Scheme}://{request.Host}{request.Path}?nestlevel={nestlevel - 1}");

                    // Makes an http call passing the activity information as http headers
                    var nestedResult = await _clientFactory.CreateClient().GetStringAsync(url);
                    await HttpContext.Response.WriteAsync(nestedResult);
                }
            }
            else
            {
                // Log a message
                _logger.LogError("Greeting nest level {nestlevel} too high", nestlevel);
                await HttpContext.Response.WriteAsync("Nest level too high, max is 5");
            }
        }
    }
    public class ObjT
    {
        public ObjT(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
        public override bool Equals(object? obj)
        {
            if (obj == null)
            {
                return false;
            }

            ObjT p = obj as ObjT;
            if ((System.Object)p == null)
            {
                return false;
            }
            return (Name == p.Name);
        }
        public override int GetHashCode()
        {
            return HashCode.Combine(Name);
        }
    }
}
